package com.editso.haier.controller.admin;

import com.editso.haier.annon.Admin;
import com.editso.haier.result.Result;
import com.editso.haier.service.FileService;
import com.editso.haier.storage.UpFileItem;
import com.editso.haier.util.Pair;
import com.editso.haier.util.Utils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Admin
@RestController
@RequestMapping("/assets")
@RequiresRoles("admin")
public class AssetsController {

    private FileService fileService;

    @Autowired
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }

    @PostMapping
    public Object upload(MultipartHttpServletRequest request) {
        boolean require = Boolean.parseBoolean(request.getParameter("require"));
        String path = request.getParameter("path");
        List<Map<String, Object>> fileNames = new ArrayList<>();
        for (String s : Utils.iterable(request.getFileNames())) {
            List<MultipartFile> files = request.getFiles(s);
            for (MultipartFile file : files) {
                UpFileItem upFileItem = UpFileItem.from(file);
                Map<String, Object> objectMap = null;
                try {
                    if (upFileItem == null) continue;
                    objectMap = Utils.asMap(new Pair("originName", upFileItem.getName()));
                    objectMap.put("saveName", fileService.save(path, upFileItem, require));
                    fileNames.add(objectMap);
                } catch (IOException e) {
                    return Result.failure(objectMap, "上传失败");
                }
            }
        }
        return Result.success(fileNames);
    }
}
